// Contain
package Pigeon

import (
	"github.com/alphazero/Go-Redis"
	"github.com/golang/glog"
	"reflect"
)

var (
	redis_ins_read  redis.Client
	redis_ins_write redis.Client
	mqConf          struct {
		Host      string
		Port      int
		MQListKey string
	}
)

func init() {

	mqConf.Host = "127.0.0.1"
	mqConf.Port = 6379
	mqConf.MQListKey = "yjnic_mq_list"
}

func SetConf(conf map[string]interface{}) {
	for key, value := range conf {
		v := reflect.ValueOf(value)
		if key == "Port" {
			mqConf.Port = int(v.Int())
		} else {
			s := reflect.ValueOf(&mqConf).Elem()
			s.FieldByName(key).SetString(v.String())
		}
	}
}

func getRedisReadIns() redis.Client {
	if redis_ins_read == nil {
		var err error
		spec := redis.DefaultSpec().Host(mqConf.Host).Port(mqConf.Port) //redis
		redis_ins_read, err = redis.NewSynchClientWithSpec(spec)
		if err != nil {
			panic(err.Error())
		}
	}
	return redis_ins_read
}

func GetRedisWriteIns() redis.Client {

	if redis_ins_write == nil {
		var e error
		spec := redis.DefaultSpec().Host(mqConf.Host).Port(mqConf.Port) //redis
		redis_ins_write, e = redis.NewSynchClientWithSpec(spec)
		if e != nil {
			panic(e.Error())
		}
	}
	return redis_ins_write
}

func Set(content []byte) error {
	redis_ins := GetRedisWriteIns()
	err := redis_ins.Lpush(mqConf.MQListKey, content)
	if err != nil {
		glog.Error("Push error:", err.Error())
		return err
	} else {
		return nil
	}
}

func Get() ([]byte, error) {
	redis_ins := getRedisReadIns()
	content, err := redis_ins.Rpop(mqConf.MQListKey)
	if err != nil {
		glog.Error("pop error:", err.Error())
	}
	return content, err
}
